package com.jiyun.jiyumall.jiyunthird.web;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.IOUtils;
import com.aliyun.oss.model.OSSObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.WritableResource;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;

@RestController
public class OssController {

    @Autowired
    private OSS ossClient;

    private static final String BUCKET_NAME = "jiyunmall";

    // 指定一个本地文件，用于一会上传使用

    // 拼接一个oss远程地址

    @GetMapping("/upload")
    public String upload() {
        try {
            ossClient.putObject(BUCKET_NAME, "钱.jpeg", new FileInputStream("G:\\qian.jpeg"));
        }
        catch (Exception e) {
            e.printStackTrace();
            return "upload fail: " + e.getMessage();
        }
        return "upload success";
    }


    @GetMapping("/download")
    public String download() {
        try {
            OSSObject ossObject = ossClient.getObject(BUCKET_NAME,
                    "钱.jpeg");
            InputStream objectContent = ossObject.getObjectContent();
            FileOutputStream fileOutputStream = new FileOutputStream("D://aa.jepg");
            byte[] bytes = new byte[1024];
            int len = 0 ;
            while((len = objectContent.read(bytes))>0){
                fileOutputStream.write(bytes,0,len);
            }
            fileOutputStream.flush();
            fileOutputStream.close();
            objectContent.close();
            return "download success, ";
        }
        catch (Exception e) {
            e.printStackTrace();
            return "download fail: " + e.getMessage();
        }
    }

}
